package com.chatroom.service.impl;

import com.chatroom.model.ChatRoom;
import com.chatroom.model.User;
import com.chatroom.repository.ChatRoomRepository;
import com.chatroom.service.ChatRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

@Service
public class ChatRoomServiceImpl implements ChatRoomService {

    private final ChatRoomRepository chatRoomRepository;

    @Autowired
    public ChatRoomServiceImpl(ChatRoomRepository chatRoomRepository) {
        this.chatRoomRepository = chatRoomRepository;
    }

    @Override
    public ChatRoom createChatRoom(String name, User creator) {
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setName(name);
        chatRoom.setCreator(creator);
        chatRoom.setRoomCode(generateUniqueRoomCode());
        chatRoom.getMembers().add(creator);
        creator.getChatRooms().add(chatRoom);
        return chatRoomRepository.save(chatRoom);
    }

    @Override
    public Optional<ChatRoom> findByRoomCode(String roomCode) {
        return chatRoomRepository.findByRoomCode(roomCode);
    }

    @Override
    public List<ChatRoom> getAllChatRooms() {
        return chatRoomRepository.findAll();
    }

    @Override
    public void addUserToChatRoom(ChatRoom chatRoom, User user) {
        chatRoom.getMembers().add(user);
        user.getChatRooms().add(chatRoom);
        chatRoomRepository.save(chatRoom);
    }

    @Override
    public Set<User> getChatRoomMembers(ChatRoom chatRoom) {
        return chatRoom.getMembers();
    }

    @Override
    public boolean existsByRoomCode(String roomCode) {
        return chatRoomRepository.existsByRoomCode(roomCode);
    }

    private String generateUniqueRoomCode() {
        Random random = new Random();
        String roomCode;
        do {
            roomCode = String.format("%06d", random.nextInt(1000000));
        } while (chatRoomRepository.existsByRoomCode(roomCode));
        return roomCode;
    }
} 